package com.landeb.shop.huo.frag;

import android.content.DialogInterface;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.app.AlertDialog;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.ExpandableListView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.landeb.shop.R;
import com.landeb.shop.huo.MyApplication;
import com.landeb.shop.huo.act.CreateOrderActivity;
import com.landeb.shop.huo.act.GoodDetailActivity;
import com.landeb.shop.huo.act.MainActivity;
import com.landeb.shop.huo.act.PayActivity;
import com.landeb.shop.huo.act.ShopDetailActivity;
import com.landeb.shop.huo.adapter.FragShoppingCartAdapter;
import com.landeb.shop.huo.bean.BeanFragShoppingCart;
import com.landeb.shop.huo.bean.BeanStatusInfo;
import com.landeb.shop.huo.httpRequest.FragShoppingCartRequest;

import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import okhttp3.OkHttpClient;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava.RxJavaCallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;
import rx.Subscriber;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;


public class ShoppingCartFragment extends Fragment implements View.OnClickListener, FragShoppingCartAdapter.ModifyInterface, FragShoppingCartAdapter.CheckInterface {

    private static final String BASE_URL = "baseUrl";

    private String mBaseUrl;

    private View view;
    private SwipeRefreshLayout mRefreshLayout;
    private Button btnEdit, btnAccount, btnCollect, btnDelete;
    private LinearLayout btnBack;
    private TextView tvTitle, tvTotalPrice;
    private ExpandableListView mExpandableListView;
    private CheckBox cbCheckAll;
    private RelativeLayout footAccountView, footEditView;
    private Button btnGoHome;

    private FragShoppingCartAdapter mAdapter;

    /**
     * 店铺列表
     */
    private List<BeanFragShoppingCart.DataBean.ListBean> mShops = new ArrayList<>();
    /**
     * 哈希表 key为店铺的id value为所购买的店铺下的产品
     */
    private Map<String, List<BeanFragShoppingCart.DataBean.ListBean.ChildBean>> mGoods = new HashMap<>();

    private int mTotalCount = 0;
    private double mTotalPrice = 0.00;
    private int editFlag = 0;


    private boolean isLoaded = false;
    private boolean isViewPrepared = false; // 标识fragment视图已经初始化完毕

    private String mUrl;
    private Retrofit mRetrofit;
    private FragShoppingCartRequest mRequest;
    private boolean onRefreshing = false;


    public ShoppingCartFragment() {

    }

    public static ShoppingCartFragment newInstance(String baseUrl) {
        ShoppingCartFragment fragment = new ShoppingCartFragment();
        Bundle args = new Bundle();
        args.putString(BASE_URL, baseUrl);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            mBaseUrl = getArguments().getString(BASE_URL);
        }

        OkHttpClient client = MyApplication.getClient();
        mUrl = MyApplication.BASE_URL;
        mRetrofit = new Retrofit.Builder()
                .baseUrl(mUrl)
                .addConverterFactory(GsonConverterFactory.create())
                .addCallAdapterFactory(RxJavaCallAdapterFactory.create())
                .client(client)
                .build();
        mRequest = mRetrofit.create(FragShoppingCartRequest.class);

    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

        view = inflater.inflate(R.layout.fragment_shopping_cart, container, false);


        initView();
        initData();
        initEvent();

        isViewPrepared = true;
        if (!isLoaded && getUserVisibleHint()) {
            refreshData();
            isLoaded = true;
        }

        return view;
    }

    private void initEvent() {

        mRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                refreshData();
            }
        });
        mRefreshLayout.setColorSchemeColors(getResources().getColor(R.color.colorPrimary));

        mAdapter = new FragShoppingCartAdapter(getContext(), mShops, mGoods);
        mAdapter.setCheckInterface(this);
        mAdapter.setModifyInterface(this);
        mExpandableListView.setAdapter(mAdapter);
//        全展开
        for (int i = 0; i < mAdapter.getGroupCount(); i++) {
            mExpandableListView.expandGroup(i);
        }

        /**swipeRefreshLayout和listView滚动冲突的解决
         * 给listview添加滚动监听  当其滑到了最顶端的一个item,将swiperefreshlayout设为enable、***、 */
        mExpandableListView.setOnScrollListener(new AbsListView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(AbsListView view, int scrollState) {

            }

            @Override
            public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
                if (firstVisibleItem == 0)
                    mRefreshLayout.setEnabled(true);
                else
                    mRefreshLayout.setEnabled(false);
            }
        });
        mExpandableListView.setOnGroupClickListener(new ExpandableListView.OnGroupClickListener() {
            @Override
            public boolean onGroupClick(ExpandableListView expandableListView, View view, int i, long l) {
//                Toast.makeText(getActivity(), mShops.get(i).getStorename(), Toast.LENGTH_SHORT).show();
                ShopDetailActivity.toAct(getActivity(), mShops.get(i).getId());
                return true;
            }
        });
        mExpandableListView.setOnChildClickListener(new ExpandableListView.OnChildClickListener() {
            @Override
            public boolean onChildClick(ExpandableListView expandableListView, View view, int i, int i1, long l) {
                // TODO: 2016/11/19 item点击逻辑

//                Toast.makeText(getActivity(),mGoods.get(mShops.get(i).getId()).get(i1).getName(),Toast.LENGTH_SHORT).show();
                String id = mGoods.get(mShops.get(i).getId()).get(i1).getGoods_id();
                String title = mGoods.get(mShops.get(i).getId()).get(i1).getName();
                String price = mGoods.get(mShops.get(i).getId()).get(i1).getPrice();

                GoodDetailActivity.toAct(getActivity(), id, title, price);


                return true;
            }
        });


        btnBack.setOnClickListener(this);
        btnEdit.setOnClickListener(this);
        btnAccount.setOnClickListener(this);
        btnCollect.setOnClickListener(this);
        btnDelete.setOnClickListener(this);
        cbCheckAll.setOnClickListener(this);
        btnGoHome.setOnClickListener(this);
    }

    private void initData() {


//        for (int i = 0; i < 4; i++) {
//            mShops.add(new ItemShopFragShoppingCartExpandListView(i + "", "天猫店铺" + (i + 1) + "号店"));
//            List<ItemGoodsFragShoppingCartExpandListView> goods = new ArrayList<>();
//            for (int j = 0; j <= i; j++) {
//                ItemGoodsFragShoppingCartExpandListView good = new ItemGoodsFragShoppingCartExpandListView(j + "", i + "号店的" + j + "号产品", "", 1.50 * (j + 1), 1);
//                goods.add(good);
//            }
//            mGoods.put(mShops.get(i).getShopId(), goods);// 将组元素的一个唯一值，这里取Id，作为子元素List的Key
//        }

    }


    private void initView() {

        mRefreshLayout = (SwipeRefreshLayout) view.findViewById(R.id.frag_shopping_cart_swipe_refresh);
        btnBack = (LinearLayout) view.findViewById(R.id.frag_shopping_cart_btn_back);
        btnEdit = (Button) view.findViewById(R.id.frag_shopping_cart_btn_edit);
        btnAccount = (Button) view.findViewById(R.id.frag_shopping_cart_btn_account);
        btnCollect = (Button) view.findViewById(R.id.frag_shopping_cart_btn_collect);
        btnDelete = (Button) view.findViewById(R.id.frag_shopping_cart_btn_delete);
        tvTitle = (TextView) view.findViewById(R.id.frag_shopping_cart_tv_title);
        tvTotalPrice = (TextView) view.findViewById(R.id.frag_shopping_cart_tv_total_price);
        mExpandableListView = (ExpandableListView) view.findViewById(R.id.frag_shopping_cart_expand_list_view);
        cbCheckAll = (CheckBox) view.findViewById(R.id.frag_shopping_cart_cb_all);
        footAccountView = (RelativeLayout) view.findViewById(R.id.frag_shopping_cart_footView_account);
        footEditView = (RelativeLayout) view.findViewById(R.id.frag_shopping_cart_footView_edit);

        btnGoHome= (Button) view.findViewById(R.id.frag_shopping_cart_btn_go_home);

//        mExpandableListView.setEmptyView(getEmptyView());
    }

    /**
     * 监测lsitview中店铺的选中状态
     */
    @Override
    public void checkedGroup(int groupPosition, boolean isChecked) {

        BeanFragShoppingCart.DataBean.ListBean shop = mShops.get(groupPosition);
        List<BeanFragShoppingCart.DataBean.ListBean.ChildBean> goods = mGoods.get(shop.getId());
//        遍历店铺下所有产品，使其选中状态与店铺选中的状态一致
        for (int i = 0; i < goods.size(); i++) {

            int is_check;
            if (isChecked) {
                is_check = 1;
            } else {
                is_check = 2;
            }
            goods.get(i).setIs_check(is_check);
//            goods.get(i).setIs_check(isChecked);
        }

//        设置全选checkbox
        if (isCheckAll())
            cbCheckAll.setChecked(true);
        else
            cbCheckAll.setChecked(false);

        mAdapter.notifyDataSetChanged();
        doCalculate();

        updateCheck();
    }

    /**
     * 监测lsitview中商品的选中状态
     */
    @Override
    public void checkedChild(int groupPosition, int childPosition, boolean isChecked) {
        // 判断改组下面的所有子元素是否是同一种状态的标识
        boolean allChildrenSameState = true;

        // 遍历所选的商品的店铺下的所有商品
        BeanFragShoppingCart.DataBean.ListBean shop = mShops.get(groupPosition);
        List<BeanFragShoppingCart.DataBean.ListBean.ChildBean> goods = mGoods.get(shop.getId());

        int is_checked;
        if (isChecked) {
            is_checked = 1;
        } else {
            is_checked = 2;
        }

        for (int i = 0; i < goods.size(); i++) {
            // 遍历所选的商品的店铺下的所有商品，查看每个商品的状态是否与所选产品的状态相同

            if (goods.get(i).getIs_check() != is_checked) {
                allChildrenSameState = false;
                break;
            }
        }

        if (allChildrenSameState) {
//            shop.setChoosed(isChecked);
            // 如果所有子元素状态相同，那么对应的组元素被设为这种统一状态
            shop.setIs_check(is_checked);
        } else {
//            shop.setChoosed(false);
            // 否则，组元素设置为未选中状态
            shop.setIs_check(2);
        }

        //设定全选按钮的状态
        if (isCheckAll()) {
            cbCheckAll.setChecked(true);// 全选
        } else {
            cbCheckAll.setChecked(false);// 全不选
        }
        mAdapter.notifyDataSetChanged();
        doCalculate();

        updateCheck();
    }

    /**
     * lsitview中商品增加按钮的回调
     */
    @Override
    public void doIncrease(int groupPosition, int childPosition, View showCountView, boolean isChecked) {

        BeanFragShoppingCart.DataBean.ListBean.ChildBean good = (BeanFragShoppingCart.DataBean.ListBean.ChildBean) mAdapter.getChild(groupPosition, childPosition);

//        点击时获取所购买商 品数++，赋值给商品数textview
        int currentCount = Integer.parseInt(good.getAmount());
        currentCount++;
        good.setAmount(currentCount + "");
        ((TextView) showCountView).setText(currentCount + "");

        mAdapter.notifyDataSetChanged();
//        计算总价和总数
        doCalculate();


        updateAmount(good.getId(), currentCount + "");

    }

    /**
     * lsitview中商品减少按钮的回调
     */
    @Override
    public void doDecrease(int groupPosition, int childPosition, View showCountView, boolean isChecked) {

        BeanFragShoppingCart.DataBean.ListBean.ChildBean good = (BeanFragShoppingCart.DataBean.ListBean.ChildBean) mAdapter.getChild(groupPosition, childPosition);
//        点击时获取所购买商 品数--，赋值给商品数textview
        int currentCount = Integer.parseInt(good.getAmount());
        if (currentCount == 1)
            return;
        currentCount--;
        good.setAmount(currentCount + "");

        ((TextView) showCountView).setText(currentCount + "");

        mAdapter.notifyDataSetChanged();
//        计算总价和总数
        doCalculate();

        updateAmount(good.getId(), currentCount + "");

    }

    @Override
    public void onClick(View v) {

        switch (v.getId()) {

            case R.id.frag_shopping_cart_btn_back:
                // TODO: 2016/10/21 返回按钮事件
//                Toast.makeText(getContext(), v.getId() + "", Toast.LENGTH_SHORT).show();
                doCalculate();

                break;

            case R.id.frag_shopping_cart_btn_edit:
                //编辑按钮的文字切换绑定底部编辑菜单和结算菜单的切换
                if (editFlag == 0) {
                    footAccountView.setVisibility(View.GONE);
                    footEditView.setVisibility(View.VISIBLE);
                    btnEdit.setText("完成");
                } else if (editFlag == 1) {
                    footAccountView.setVisibility(View.VISIBLE);
                    footEditView.setVisibility(View.GONE);
                    btnEdit.setText("编辑");
                }
                //其余得到循环执行上面2个不同的功能
                editFlag = (editFlag + 1) % 2;
                break;

            case R.id.frag_shopping_cart_cb_all:
//                全选商品
                doCheckAll();
                break;

            case R.id.frag_shopping_cart_btn_account:
                // TODO: 2016/10/21 结算逻辑

                if (mTotalCount == 0) {
                    Toast.makeText(getContext(), "请选择要支付的商品", Toast.LENGTH_SHORT).show();
                    return;
                }

//                AlertDialog.Builder payBuilder = new AlertDialog.Builder(getContext());
//
//                payBuilder.setTitle("操作提示");
//                payBuilder.setMessage("总计:\n" + mTotalCount + "种商品\n" + mTotalPrice + "元");
//
//                payBuilder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
//                    @Override
//                    public void onClick(DialogInterface dialog, int which) {
//
//                    }
//                });
//
//                payBuilder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
//                    @Override
//                    public void onClick(DialogInterface dialog, int which) {
//
//                        PayActivity.toAct(getActivity());
//                    }
//                });
//                payBuilder.create().show();

                CreateOrderActivity.toAct(getContext(), whichGoodsIsChecked());

                break;

            case R.id.frag_shopping_cart_btn_delete:

                if (mTotalCount == 0) {
                    Toast.makeText(getContext(), "请选择要移除的商品", Toast.LENGTH_SHORT).show();
                    return;
                }

                AlertDialog.Builder deleteBuilder = new AlertDialog.Builder(getContext());

                deleteBuilder.setTitle("操作提示");
                deleteBuilder.setMessage("您确定要将这些商品从购物车中移除吗？");

                deleteBuilder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {

                    }
                });

                deleteBuilder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {

                        updateDeleted();
//                        doDelete();
//                        isListViewEmpty();
                        refreshData();
                    }
                });
                deleteBuilder.create().show();
                break;

            case R.id.frag_shopping_cart_btn_collect:
                if (mTotalCount == 0) {
                    Toast.makeText(getContext(), "请选择要收藏的商品", Toast.LENGTH_SHORT).show();
                    return;
                }
                // TODO: 2016/10/21 收藏逻辑
                Toast.makeText(getContext(), "保存成功", Toast.LENGTH_SHORT).show();
                break;


            case R.id.frag_shopping_cart_btn_go_home:
                ((MainActivity)getActivity()).goPage(MainActivity.HOME_PAGE);
                Log.e( "gohome: ", "xxxxxxxx");
                break;
        }

    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();

        mShops.clear();
        mGoods.clear();
        mAdapter = null;
    }

    /**
     * 全部选中的方法
     */
    private void doCheckAll() {

        for (int i = 0; i < mShops.size(); i++) {

            int is_checked;
            if (cbCheckAll.isChecked()) {
                is_checked = 1;
            } else {
                is_checked = 2;
            }

            BeanFragShoppingCart.DataBean.ListBean shop = mShops.get(i);
            shop.setIs_check(is_checked);
//            mShops.get(i).setChoosed(cbCheckAll.isChecked());
            List<BeanFragShoppingCart.DataBean.ListBean.ChildBean> goods = mGoods.get(shop.getId());

            for (int j = 0; j < goods.size(); j++) {
//                goods.get(j).setChoosed(cbCheckAll.isChecked());
                goods.get(j).setIs_check(is_checked);
            }
        }

        mAdapter.notifyDataSetChanged();

        doCalculate();

        updateCheck();
    }

    /**
     * 判断是否全部选中的方法
     */
    private boolean isCheckAll() {

        for (BeanFragShoppingCart.DataBean.ListBean shop : mShops) {
            if (shop.getIs_check() == 2)
                return false;
        }
        return true;
    }

    /**
     * 删除方法  遍历选中的项目存到list 然后removeAll()
     */
    private void doDelete() {
        // 待删除的组元素列表
        List<BeanFragShoppingCart.DataBean.ListBean> toBeDeleteGroups = new ArrayList<>();

        for (int i = 0; i < mShops.size(); i++) {
            BeanFragShoppingCart.DataBean.ListBean shop = mShops.get(i);

            if (shop.getIs_check() == 1) {
                toBeDeleteGroups.add(shop);
            }

            // 待删除的子元素列表
            List<BeanFragShoppingCart.DataBean.ListBean.ChildBean> toBeDeleteGoods = new ArrayList<>();

            List<BeanFragShoppingCart.DataBean.ListBean.ChildBean> gooods = mGoods.get(shop.getId());

            for (int j = 0; j < gooods.size(); j++) {
                if (gooods.get(j).getIs_check() == 1) {
                    toBeDeleteGoods.add(gooods.get(j));
                }
            }
            gooods.removeAll(toBeDeleteGoods);
        }
        mShops.removeAll(toBeDeleteGroups);

        //记得重新设置购物车
        setCartNum();

        mAdapter.notifyDataSetChanged();


    }


    /**
     * 计算购物车中  被选中的  商品数和总价的方法  并且更新视图  更新底部购物车数量 总价
     */
    private void doCalculate() {

        mTotalCount = 0;
        mTotalPrice = 0.00;
        for (int i = 0; i < mShops.size(); i++) {
            BeanFragShoppingCart.DataBean.ListBean shop = mShops.get(i);
            List<BeanFragShoppingCart.DataBean.ListBean.ChildBean> goods = mGoods.get(shop.getId());
            for (int j = 0; j < goods.size(); j++) {
                BeanFragShoppingCart.DataBean.ListBean.ChildBean good = goods.get(j);
                if (good.getIs_check() == 1) {
                    mTotalCount++;
                    mTotalPrice += Double.valueOf(good.getPrice()) * Integer.valueOf(good.getAmount());
                }
            }
        }

//        设置显示总价

//        保留两位小数
        String doublePrice = String.format("%.2f", mTotalPrice);

        tvTotalPrice.setText("¥" + doublePrice);
//        按钮显示总价
//        btnAccount.setText("去支付(" + doublePrice + ")");
        //计算购物车的金额为0时候清空购物车的视图
        if (mTotalCount == 0) {
            setCartNum();
        } else {
//            顶部显示商品数量
//            tvTitle.setText("购物车" + "(" + mTotalCount + ")");
        }
    }

    /**
     * 更新购物车视图，顶部购物车数量 的方法
     */
    private void setCartNum() {
        int allGoodsNum = 0;
        for (int i = 0; i < mShops.size(); i++) {
            // TODO: 2016/10/21 ?????

            int shopChecked;
            if (cbCheckAll.isChecked()) {
                shopChecked = 1;
            } else {
                shopChecked = 2;
            }

            BeanFragShoppingCart.DataBean.ListBean shop = mShops.get(i);
//            mShops.get(i).setChoosed(cbCheckAll.isChecked());
            shop.setIs_check(shopChecked);
//            ItemShopFragShoppingCartExpandListView shop = mShops.get(i);
            List<BeanFragShoppingCart.DataBean.ListBean.ChildBean> goods = mGoods.get(shop.getId());

            for (BeanFragShoppingCart.DataBean.ListBean.ChildBean good : goods) {
                allGoodsNum += 1;
            }
        }

        //购物车已清空
        if (allGoodsNum == 0) {
            clearCart();
        } else {
//            tvTitle.setText("购物车" + "(" + allGoodsNum + ")");
        }
    }

    /**
     * 购物车全部清空时调用方法
     */
    private void clearCart() {
        // TODO: 2016/10/21 购物车全空时调用方法 更新界面
    }

    //    获取选中的goodID 拼接字符串
    private String whichGoodsIsChecked() {

        StringBuilder builder = new StringBuilder();

        for (BeanFragShoppingCart.DataBean.ListBean shop : mShops) {
            List<BeanFragShoppingCart.DataBean.ListBean.ChildBean> goods = mGoods.get(shop.getId());
            for (BeanFragShoppingCart.DataBean.ListBean.ChildBean good : goods) {
                if (good.getIs_check() == 1) {
                    builder.append(good.getId() + ",");
                }
            }
        }

        return builder.toString();
    }

    //    获取未选中的goodID 拼接字符串
    private String whichGoodsIsUnchecked() {

        StringBuilder builder = new StringBuilder();

        for (BeanFragShoppingCart.DataBean.ListBean shop : mShops) {
            List<BeanFragShoppingCart.DataBean.ListBean.ChildBean> goods = mGoods.get(shop.getId());
            for (BeanFragShoppingCart.DataBean.ListBean.ChildBean good : goods) {
                if (good.getIs_check() == 2) {
                    builder.append(good.getId() + ",");
                }
            }
        }

        return builder.toString();
    }

    //    上传选中和未选中项目 在点击项目 点击店铺 点击全选时触发
    private void updateCheck() {

        String checked = whichGoodsIsChecked();
        String unchecked = whichGoodsIsUnchecked();

        mRequest.updateChecked(checked, unchecked)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Subscriber<BeanStatusInfo>() {
                    @Override
                    public void onCompleted() {
                        Log.e("updateChecked", "onCompleted: ");
                    }

                    @Override
                    public void onError(Throwable e) {
                        Log.e("updateChecked", "onError: " + e.toString());

                    }

                    @Override
                    public void onNext(BeanStatusInfo beanStatusInfo) {

                    }
                });
    }

    //上传 某项目的购买数量  点击按钮时触发
    private void updateAmount(String cart_id, String amount) {

        mRequest.updateAmount(cart_id, amount)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Subscriber<BeanStatusInfo>() {
                    @Override
                    public void onCompleted() {
                        Log.e("updateAmount", "onCompleted: ");
                    }

                    @Override
                    public void onError(Throwable e) {
                        Log.e("updateAmount", "onError: " + e.toString());

                    }

                    @Override
                    public void onNext(BeanStatusInfo beanStatusInfo) {

                    }
                });

    }

    //上传要删除的项目id
    private void updateDeleted() {

        String checked = whichGoodsIsChecked();

        mRequest.GoodsDelete(checked)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Subscriber<BeanStatusInfo>() {
                    @Override
                    public void onCompleted() {
                        Log.e("GoodsDelete", "onCompleted: ");
                    }

                    @Override
                    public void onError(Throwable e) {
                        Log.e("GoodsDelete", "onError: " + e.toString());

                    }

                    @Override
                    public void onNext(BeanStatusInfo beanStatusInfo) {
                    }
                });
    }


    private void refreshData() {

        if (!onRefreshing) {

            onRefreshing = true;

            mRequest.getCartData()
                    .subscribeOn(Schedulers.io())
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribe(new Subscriber<BeanFragShoppingCart>() {
                        @Override
                        public void onCompleted() {
                            Log.e("refreshData", "successed");
                            onRefreshing = false;
                            mRefreshLayout.setRefreshing(false);
                        }

                        @Override
                        public void onError(Throwable e) {
                            Log.e("refreshData", "error" + e.toString());
                            onRefreshing = false;
                            mRefreshLayout.setRefreshing(false);

                        }

                        @Override
                        public void onNext(BeanFragShoppingCart beanFragShoppingCart) {

                            if (beanFragShoppingCart.getStatus() == 1) {


                                mShops.clear();
                                mGoods.clear();
                                for (int i = 0; i < beanFragShoppingCart.getData().getList().size(); i++) {

                                    BeanFragShoppingCart.DataBean.ListBean shop = beanFragShoppingCart.getData().getList().get(i);
                                    List<BeanFragShoppingCart.DataBean.ListBean.ChildBean> goods = beanFragShoppingCart.getData().getList().get(i).getChild();

                                    mShops.add(shop);

                                    mGoods.put(shop.getId(), goods);

                                    mAdapter.notifyDataSetChanged();

                                    for (int j = 0; j < mAdapter.getGroupCount(); j++) {
                                        mExpandableListView.expandGroup(j);
                                    }

                                    doCalculate();

                                }

                            } else {
                                Toast.makeText(getActivity(), beanFragShoppingCart.getInfo(), Toast.LENGTH_SHORT).show();
                            }

                            isListViewEmpty();


                        }
                    });

        }

    }

    private void isListViewEmpty() {

        Log.e("isListViewEmpty: ", "done");

        Log.e("Empty: ", mShops.size() + "+++++" + mGoods.size());

        if (mShops.isEmpty() && mGoods.isEmpty()) {

            mExpandableListView.setVisibility(View.GONE);

        } else {

            mExpandableListView.setVisibility(View.VISIBLE);

        }

    }

    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);
        if (isVisibleToUser) {

            if (isViewPrepared && !isLoaded) {
                refreshData();
                isLoaded = true;
            }
        }

    }

    @Override
    public void onResume() {
        super.onResume();
        refreshData();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();

        isViewPrepared = false;
        isLoaded = false;

    }


}


